import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
    todos:JSON.parse(localStorage.getItem('todos')) || []
}

const mutations = {
    UPDATEISOVER(state,index){
        state.todos[index].isOver = !state.todos[index].isOver
    },
    DELETEONE(state,index){
        state.todos.splice(index,1)
    },
    ALLCHECKED(state,check){
        state.todos.forEach(item => {
            item.isOver = check
            return item 
        });
    },
    CLEAROVER(state){
        state.todos = state.todos.filter(item=>!item.isOver)
    },
    ADDTODO(state,todo){
        state.todos.unshift(todo)
    }
}

const actions = {
    // 更改一个isOver
    updateIsover({commit},index){
        commit('UPDATEISOVER',index)
    },
    // 删除一条todo
    deleteOne({commit},index){
        console.log(index);
        commit('DELETEONE',index)
    }   ,
    allChecked({commit},check){
        commit('ALLCHECKED',check)
    },
    clearOver({commit}){
        commit('CLEAROVER')
    },
    addTodo({commit,state},content){
        const result = state.todos.find(item=>item.content===content)
        if(content && !result){
            const newTodo = {
                id:Date.now(),
                content:content,
                isOver:false
            }
            commit('ADDTODO',newTodo)
        }else{
            alert('内容重复或为空，请重新输入')
        }
    }
}

const getters = {
    todos(){
        return 0
    }
}

export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
})